import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Select } from 'antd';
import { RangeDateC, PrimaryC, TableC, NoDataC } from '../../../../comps';
import moment from 'moment';
import style from './index.less';
import uuid from 'es6-uuid';

@Form.create()
@connect(({ loading, ProductAnalysisM }) => ({ loading, ProductAnalysisM }))
export default class CashDetailC extends PureComponent {
  state = {
    columns: [
      { dataIndex: 'assetType', title: '资产类型', key: 'assetType' },
      { dataIndex: 'date', title: '日期', key: 'date' },
      { dataIndex: 'bondCode', title: '证券代码', key: 'bondCode' },
      { dataIndex: 'bondAbbreviation', title: '证券简称', key: 'bondAbbreviation' },
      { dataIndex: 'direction', title: '现金流方向', key: 'direction' },
      { dataIndex: 'money', title: '金额', key: 'money' },
      { dataIndex: 'eventType', title: '事件类型', key: 'eventType' },
    ],
    dataSource: [],
    total: 0,
    currentPage: 1, //页码
    numInPage: 10, //每页条数
    beginDate: '',
    endDate: '',
    accountData: { inflowAmt: undefined, outflowAmt: undefined }, // 汇总信息
  };
  componentDidMount() {
    this.getTableData(this.props.rootId);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.rootId != this.props.rootId) {
      this.getTableData(nextProps.rootId);
    }
  }

  getTableData = (rootId) => {
    const { dispatch } = this.props;
    const { currentPage, numInPage, beginDate, endDate } = this.state;
    if (!rootId) return;
    let value = {
      type: 'workstation',
      currentPage: currentPage,
      numInPage: numInPage,
      eventType: ['DQ', 'FX', 'HB', 'XQ'],
      weightSetting: '1',
      portfolioId: [rootId],
      beginDate: beginDate ? beginDate.format('YYYYMMDD') : moment().add(0, 'day').format('YYYYMMDD'),
      endDate: endDate ? endDate.format('YYYYMMDD') : moment().add(1, 'year').subtract(1, 'day').format('YYYYMMDD'),
    };
    dispatch({
      type: 'ProductAnalysisM/cashFlowDetails',
      payload: {
        ...value,
      },
      callback: (data) => {
        if (data && data.dataSource.length) {
          data.dataSource.map((item, index) => {
            item.key = uuid(10);
          });
          this.setState({
            dataSource: data.dataSource,
            total: data.pageInfo.total,
          });
        } else {
          this.setState({
            dataSource: [],
            total: 0,
          });
        }
      },
    });
    // 获取汇总信息
    dispatch({
      type: 'ProductAnalysisM/getAccount',
      payload: {
        ...value,
      },
      callback: (data) => {
        this.setState({
          accountData: data,
        });
        this.props.getCashData(Number(data.inflowAmt).toFixed(4), Number(data.outflowAmt).toFixed(4));
      },
    });
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    let data = columns;
    if (data && data.length) {
      columns.map((item) => {
        if (item.key == 'direction') {
          item.render = (text, record) => {
            if (record.inflowAmt != '0' && record.inflowAmt != null && record.inflowAmt != undefined) {
              return '流入';
            } else if (record.outflowAmt != '0' && record.outflowAmt != null && record.outflowAmt != undefined) {
              return '流出';
            } else {
              return '--';
            }
          };
        }
        if (item.key == 'money') {
          item.render = (text, record) => {
            if (record.inflowAmt != '0' && record.inflowAmt != null && record.inflowAmt != undefined) {
              return Number(record.inflowAmt).toFixed(2);
            } else if (record.outflowAmt != '0' && record.outflowAmt != null && record.outflowAmt != undefined) {
              return Number(record.outflowAmt).toFixed(2);
            } else {
              return '--';
            }
          };
        }
      });
    }
    return data;
  };

  //表格页码排序改变调用
  onPageChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState({
      currentPage: current,
      numInPage: pageSize,
    });
  };

  onClick = () => {
    this.setState(
      {
        dataSource: [],
        total: 0,
        currentPage: 1, //页码
        numInPage: 10, //每页条数
      },
      () => {
        this.getTableData(this.props.rootId);
      },
    );
  };

  render() {
    const { columns, dataSource, currentPage, total, numInPage, accountData } = this.state;
    const { loading, rootId } = this.props;
    const formItemLayout = {
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 18,
      },
    };
    const newColumns = this.changeColumns(columns);
    return (
      <div className={style.cashDetail}>
        {rootId ? (
          <div>
            <div className={style.selectbox}>
              <div className={style.select}>
                <div style={{ width: '400px' }}>
                  <RangeDateC
                    form={this.props.form}
                    dataIndex={['beginDate', 'endDate']}
                    title='日期区间'
                    initialValue={[moment().add(0, 'day'), moment().add(1, 'year').subtract(1, 'day')]}
                    hasDataBD={moment().add(0, 'day')}
                    disableFuture={false}
                    formItemLayout={formItemLayout}
                    onChange={(e) => {
                      this.setState({
                        beginDate: e[0],
                        endDate: e[1],
                      });
                    }}
                  />
                </div>
              </div>
              <PrimaryC title={'查询'} onClick={this.onClick} />
            </div>
            <div className={style.tip}>
              <span>
                区间现金流流入：<span className={style.num}>{accountData.inflowAmt ? Number(accountData.inflowAmt).toFixed(4) : '--'}万元</span>
              </span>
              <span className={style.line}></span>
              <span>
                区间现金流流出：<span className={style.num}>{accountData.outflowAmt ? Number(accountData.outflowAmt).toFixed(4) : '--'}万元</span>
              </span>
            </div>
            <div style={{ marginTop: '16px' }}>
              <TableC
                columns={newColumns}
                dataSource={dataSource}
                rowKey='key'
                current={currentPage}
                pageSize={numInPage}
                onChange={this.onPageChange}
                loading={loading.effects['forecast/cashFlowDetails']}
              ></TableC>
            </div>
          </div>
        ) : (
          <NoDataC />
        )}
      </div>
    );
  }
}
